package com.netease.nim.uikit.business.ait.selector

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.netease.nim.uikit.R
import com.netease.nim.uikit.api.NimUIKit
import com.netease.nim.uikit.api.model.SimpleCallback
import com.netease.nim.uikit.api.wrapper.NimUserInfoProvider
import com.netease.nim.uikit.business.ait.selector.adapter.AitContactAdapter
import com.netease.nim.uikit.business.ait.selector.model.AitContactItem
import com.netease.nim.uikit.business.ait.selector.model.ItemType
import com.netease.nim.uikit.business.team.helper.TeamHelper
import com.netease.nim.uikit.common.activity.UI
import com.netease.nim.uikit.common.ui.recyclerview.listener.OnItemClickListener
import com.netease.nimlib.sdk.robot.model.NimRobotInfo
import com.netease.nimlib.sdk.team.model.Team
import com.netease.nimlib.sdk.team.model.TeamMember
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import java.util.ArrayList

class AitContactSelectorActivity2 : UI() {

    private var adapter: AitContactAdapter? = null

    private var teamId: String? = null

    private var addRobot = false

    private var items: MutableList<AitContactItem<*>>? = null

    companion object {
        private val EXTRA_ID = "EXTRA_ID"
        private val EXTRA_ROBOT = "EXTRA_ROBOT"

        val REQUEST_CODE = 0x10
        val RESULT_TYPE = "type"
        val RESULT_DATA = "data"
        fun start(context: Context, tid: String?, addRobot: Boolean) {
            val intent = Intent(context, AitContactSelectorActivity2::class.java)
            if (tid != null) {
                intent.putExtra(EXTRA_ID, tid)
            }
            if (addRobot) {
                intent.putExtra(EXTRA_ROBOT, true)
            }
            (context as Activity).startActivityForResult(intent, REQUEST_CODE)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.nim_team_member_list_layout)
        parseIntent()
        initViews()
        initData()
    }

    private fun initViews() {
        val recyclerView = findViewById<RecyclerView>(R.id.member_list)
        recyclerView.layoutManager = LinearLayoutManager(this)
        initAdapter(recyclerView)
        findViewById<View>(R.id.tvCancel).setOnClickListener { finish() }
        val etSearch = findViewById<EditText>(R.id.etSearch)
        etSearch.addTextChangedListener {
            if (!it.isNullOrEmpty()) {
                if (!items.isNullOrEmpty()) {
                    adapter?.setNewData(items?.filter { item ->
                        when (item.viewType) {
                            ItemType.TEAM_MEMBER -> {
                                val teamNick =
                                    TeamHelper.getTeamMemberDisplayName(
                                        teamId,
                                        (item.model as TeamMember).account
                                    )
                                teamNick.contains(it.toString())
                            }
                            ItemType.SIMPLE_LABEL -> {
                                true
                            }
                            else -> {
                                it.toString().isEmpty()
                            }
                        }
                    })
                }
            } else {
                adapter?.setNewData(items)
            }
        }
//        ToolBarOptions options = new NimToolBarOptions();
//        options.titleString = "选择提醒的人";
//        setToolBar(R.id.toolbar, options);
    }

    private fun initAdapter(recyclerView: RecyclerView) {
        items = ArrayList()
        adapter = AitContactAdapter(recyclerView, items)
        recyclerView.adapter = adapter
        val noDividerViewTypes: MutableList<Int> = ArrayList(1)
        noDividerViewTypes.add(ItemType.SIMPLE_LABEL)
        recyclerView.addItemDecoration(
            AitContactDecoration(
                this,
                LinearLayoutManager.VERTICAL,
                noDividerViewTypes
            )
        )
        recyclerView.addOnItemTouchListener(object : OnItemClickListener<AitContactAdapter?>() {
            override fun onItemClick(adapter: AitContactAdapter?, view: View?, position: Int) {
                val item = adapter?.getItem(position)
                val intent = Intent()
                intent.putExtra(RESULT_TYPE, item?.viewType)
                if (item?.viewType == ItemType.TEAM_MEMBER) {
                    intent.putExtra(RESULT_DATA, item.model as TeamMember)
                } else if (item?.viewType == ItemType.ROBOT) {
                    intent.putExtra(RESULT_DATA, item.model as NimRobotInfo)
                }
                setResult(RESULT_OK, intent)
                finish()
            }
        })
    }

    private fun parseIntent() {
        val intent = intent
        teamId = intent.getStringExtra(EXTRA_ID)
        addRobot = intent.getBooleanExtra(EXTRA_ROBOT, false)
    }

    private fun initData() {
        items = ArrayList()
        if (addRobot) {
            initRobot()
        }
        if (teamId != null) {
            initTeamMemberAsync()
        } else {
            //data 加载结束，通知更新
            adapter!!.setNewData(items)
        }
    }

    private fun initRobot() {
        val robots = NimUIKit.getRobotInfoProvider().allRobotAccounts
        if (robots != null && robots.isNotEmpty()) {
            items!!.add(0, AitContactItem<Any?>(ItemType.SIMPLE_LABEL, "机器人"))
            for (robot in robots) {
                items!!.add(AitContactItem<Any?>(ItemType.ROBOT, robot))
            }
        }
    }

    private fun initTeamMemberAsync() {
        val t = NimUIKit.getTeamProvider().getTeamById(teamId)
        if (t != null) {
            updateTeamMember(t)
        } else {
            NimUIKit.getTeamProvider().fetchTeamById(
                teamId
            ) { success, result, _ ->
                if (success && result != null) {
                    // 继续加载群成员
                    updateTeamMember(result)
                } else {
                    //data 加载结束，通知更新
                    adapter!!.setNewData(items)
                }
            }
        }
    }

    private fun updateTeamMember(team: Team) {
        NimUIKit.getTeamProvider()
            .fetchTeamMemberList(
                teamId
            ) { success, members, _ ->
                if (success && members != null && members.isNotEmpty()) {
                    // filter self
                    for (member in members) {
                        if (member.account == NimUIKit.getAccount()) {
                            members.remove(member)
                            break
                        }
                    }
                    if (members.isNotEmpty()) {
                        items!!.add(AitContactItem<Any?>(ItemType.SIMPLE_LABEL, "群成员"))
                        for (member in members) {
                            items!!.add(AitContactItem<Any?>(ItemType.TEAM_MEMBER, member))
                        }
                    }
                }
                //data 加载结束，通知更新
                adapter!!.setNewData(items)
            }
    }
}